package com.calvin.study.rabbitmq;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.calvin.study.service.StorageService;
import com.rabbitmq.client.Channel;

import cloud.alibaba.study.dto.storage.StorageDto;
import cloud.alibaba.study.entity.order.Order;
import cloud.alibaba.study.entity.storage.Storage;

@Component
public class OrderConsumer {
	
	@Autowired
	private StorageService storageService;
	
	//库存预占
	@RabbitListener(queues="storage.reserved.queue")
	@RabbitHandler
	public void storageReservedListener(Order order, Channel channel,Message message) throws Exception {
		long deliveryTag = 0 ;
		try {
			deliveryTag = message.getMessageProperties().getDeliveryTag();
			//完成库存预占
			Storage storage = new Storage();
			storage.setProductId(order.getProductId());
			storage.setReserved(order.getCount());
			storageService.storageReserved(storage);
			
			channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
		} catch (Exception e) {
			//如果发生异常,则进行消费重试机制
			channel.basicNack(deliveryTag, false, false);
		}
	}
	
	
	//解除库存预占
	@RabbitListener(queues="order.release.order.queue")
	@RabbitHandler
	public void orderListener(Order order, Channel channel,Message message) throws Exception {
		long deliveryTag = 0 ;
		try {
			//当前消息是否重新派发
			//Boolean redelivered = message.getMessageProperties().getRedelivered();
			deliveryTag = message.getMessageProperties().getDeliveryTag();
			//完成扣减库存服务
			StorageDto input = new StorageDto();
			input.setProductId(order.getProductId());
			//storage.setUsed(order.getCount());
			storageService.storageUnReserved(input);
			//通知订单服务修改订单状态
			channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
		} catch (Exception e) {
			//如果发生异常,则进行消费重试机制
			channel.basicNack(deliveryTag, false, false);
		}
	}
	

}
